package com.imisty.batch;

import org.junit.Test;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class BatchTestOne {


    @Test
    public void jdbcInsertOneByOne() {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = JdbcUtils.getConnection();
            JdbcUtils.begin(connection);
            String sql = "insert into t_user(username,password) values (?,?)";
            statement = connection.prepareStatement(sql);
            long beginTime = System.currentTimeMillis();
            for (int i = 0;i<= 10000;i++){
                statement.setString(1,"hello"+i);
                statement.setString(2,"world"+i);
                statement.executeUpdate();
            }
            JdbcUtils.commit(connection);
            long endTime = System.currentTimeMillis();
            System.out.println("totalTime : "+(endTime - beginTime));

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void jdbcInsertBatch(){
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = JdbcUtils.getConnection();
            JdbcUtils.begin(connection);
            String sql = "insert into t_user(username,password) values (?,?)";
            statement = connection.prepareStatement(sql);
            long beginTime = System.currentTimeMillis();
            for (int i = 0;i<= 10000;i++){
                statement.setString(1,"hello"+i);
                statement.setString(2,"world"+i);
                //添加sql批处理
                statement.addBatch();
                //每500条批量执行
                if ((i % 500) == 0){
                    statement.executeBatch();
                    statement.clearBatch();
                }
            }
            //执行剩下的sql
            if(10000 % 500 != 0){
                statement.executeBatch();
                statement.clearBatch();
            }
            JdbcUtils.commit(connection);
            long endTime = System.currentTimeMillis();
            System.out.println("totalTime : "+(endTime - beginTime));

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

}
